<?php

declare(strict_types=1);
/**
 * This file is part of MineAdmin.
 *
 * @link     https://www.mineadmin.com
 * @document https://doc.mineadmin.com
 * @contact  root@imoi.cn
 * @license  https://github.com/mineadmin/MineAdmin/blob/master/LICENSE
 */

namespace App\Repository\Course;

use App\Model\Course;
use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Annotation\Transactional;

/**
 * Class CourseRepository.
 * @extends IRepository<School>
 */
final class CourseRepository extends IRepository
{
    public function __construct(protected readonly Course $model) {}
    public function handleSearch(Builder $query, array $params): Builder
    {
        $with = $params['with'] ?? [];
        $with[] = 'creator';
        $with[] = 'categorys';
        $with[] = 'tags';
        return $query
            ->with($with)
            ->when(
                Arr::get($params, 'title'),
                static function (Builder $query, $title) {
                    $query->where('title', 'like', '%' . $title . '%');
                }
            );
    }

    #[Transactional()]
    public function create(array $data): mixed
    {
        /**
         * @var Course $model
         */
        $model = parent::create($data);
        $model->categorys()->sync($data['category_ids'] ?? []);
        $model->tags()->sync($data['tag_ids'] ?? []);
        return $model;
    }

    #[Transactional()]
    public function updateById(mixed $id, array $data): bool
    {
        $res = parent::updateById($id, $data);
        $model = $this->findById($id);
        $model->categorys()->sync($data['category_ids'] ?? []);
        $model->tags()->sync($data['tag_ids'] ?? []);
        return $res;
    }
}
